from django.shortcuts import render
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django_redis import get_redis_connection
from django.contrib.auth import login
from django import http
import json
import re
import logging

from oauth.models import OAuthQQUser
from users.models import User
from oauth.utils import generate_access_token, check_access_token
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class QQUserView(View):
    """第二步"""
    """用户扫码登录的回调处理"""
    def get(self, request):
        # 提取参数
        code = request.GET.get('code')
        # 校验参数
        if not code:
            return http.JsonResponse({'code': 400, 'errmsg': '数据无效'})

        qq_oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 需要联网获取,所以需要try
            # 根据获取的code提取access_token
            access_token = qq_oauth.get_access_token(code)
            # 根据获取的access_token提取openid
            openid = qq_oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据访问有误'})

        # 1.判断用户是否存在
        # 1.1 第一次使用,用户存在,没有保存openid
        # 1.2 用户不存在,先绑定用户,再保存openid
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            logger.error(e)
            # 对openid编码成token
            token = generate_access_token(openid)

            return http.JsonResponse({'code': 300, 'errmsg': '数据不存在', 'access_token': token})

        # 状态保持
        login(request, qq_user.user)
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', qq_user.user.username)
        return response

    def post(self, request):
        # 提取参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        password = json_dict.get('password')
        sms_code = json_dict.get('sms_code')
        access_token = json_dict.get('access_token')
        # 校验参数
        if not all([mobile, password, sms_code, access_token]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误'})

        conn = get_redis_connection('verify_code')
        sms_code_server = conn.get('sms_%s' % mobile)
        if not sms_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '验证码过期'})
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code': 400, 'errmsg': '验证码输入有误'})

        # 对access_token解码成openid
        openid = check_access_token(access_token)

        # 1.判断用户是否存在
        # 1.1 第一次使用,用户存在,没有保存openid
        # 1.2 用户不存在,先绑定用户,再保存openid
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            logger.error(e)
            try:
                user = User.objects.create_user(username=mobile, password=password, mobile=mobile)
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        else:
            if not user.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg': '密码或手机号有误'})

        try:
            OAuthQQUser.objects.create(openid=openid, user_id=user.id)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})
        # 状态保持
        login(request, user)
        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 前端首页用户显示
        response.set_cookie('username', user.username, max_age=3600*14)
        # return response
        # 登录合并未登录的购物车
        return merge_cart_cookie_to_redis(request, user, response)


class QQUrlView(View):
    """第一步"""
    """获取qq网页页面"""
    def get(self, request):
        next = request.GET.get('next')

        qq_oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state=next)

        login_url = qq_oauth.get_qq_url()
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': login_url})



